import React, { Component } from 'react'
import { Form, Input, Button, message, Row, Col } from 'antd'
import { MailOutlined } from '@ant-design/icons'

import { address } from '@/Utils/apiConfig'
import request from '@/Utils/fecth'
import { TOKEN, PUBLIC_KEY } from '@/Utils/CONST'
import { cryptoData } from '@/Utils/common'
import regexp from '@/Utils/regexp'

import './login.less'

const { login, loginApi } = address

export default class Login extends Component {
  constructor(props) {
    super(props)
    this.state = {
      loading: false,
      btnLoading: false,
      hasSend: false, // 是否已发送验证码
      step: 1,
      expired: false,
      mail_address: '',
      currentTime: totalTime,
    }
    this.publicKey = ''
  }

  componentDidMount() {
    this.getPublicKey()
  }

  componentWillUnmount() {
    this.timer && this.stopTimer()
  }

  /**
   * 获取邮箱验证码
   */
  getCode = async() => {
    this.setState({
      btnLoading: true,
    })
    const { code } = await request().get(loginApi.getEmailCode)
    this.setState({
      btnLoading: false,
    })
    if (code === 200) {
      message.success('验证码已成功发送至您的邮箱！')
      this.startTimer()
      this.setState({
        hasSend: true,
      })
    }
  }

  stopTimer() {
    clearInterval(this.timer)
    this.timer = null
    this.setState({
      hasSend: false,
      currentTime: totalTime,
    })
  }

  startTimer() {
    let { currentTime } = this.state
    this.timer = setInterval(() => {
      currentTime = currentTime - 1
      if (currentTime <= 0) {
        this.stopTimer()
      } else {
        this.setState({
          currentTime,
        })
      }
    }, 1000)
  }

  async getPublicKey() {
    this.setState({
      loading: true,
    })
    const { status, data } = await request().get(address.getPublicKey)
    this.setState({
      loading: false,
    })
    if (status === 200) {
      this.publicKey = data || ''
      localStorage.setItem(PUBLIC_KEY, this.publicKey)
    }
  }

  // 提交表单
  handleSubmit = async(values) => {
    this.setState({
      loading: true,
    })
    const { status, data = {}} = await request().post(login, cryptoData(JSON.stringify(values), this.publicKey))
    this.setState({
      loading: false,
    })
    if (status === 200 && data.token) {
      const userInfo = (data.user || {})
      const userStatus = userInfo.status
      const mail_address = userInfo.mail_address
      const token = data.token
      localStorage.setItem(TOKEN, token)
      if (userStatus === 'UNACTIVATED') {
        // 创建时间不是当天 则超过90天
        this.setState({
          expired: !userInfo.initial_flag, // initial_flag -->true说明是第一次登录 false需要改密码则是超过90天
        })
        // 第一次登录需修改密码
        this.oldPwd = values._pwd
        this.oldName = values.name
        this.setState({
          step: 2,
        })
        message.info(`${userInfo.initial_flag
          ? '用户第一次登录，请先设置新密码'
          : '为保证账户安全，每90天须更换密码'}`)
      } else {
        // 进行邮箱验证
        this.setState({
          step: 3,
          mail_address,
        })
      }
    }
  }

  /**
   *
   * @param {修改密码} values
   */
   onModifyPwdFinish = async(values) => {
     this.setState({
       loading: true,
     })
     const { code } = await request().post(address.account.modifyPwd, cryptoData(JSON.stringify({
       newPwd: values.newPwd,
       oldPwd: this.oldPwd,
     }), localStorage.getItem(PUBLIC_KEY)))
     if (code === 200) {
       message.success('修改成功')
       // 再次调登录接口
       await this.handleSubmit({
         name: this.oldName,
         _pwd: values.newPwd,
       })
     }
     this.setState({
       loading: false,
     })
   }

  /**
   *
   * @param {验证邮箱} values
   */
  onEmailFormFinish = async(values = {}) => {
    this.setState({
      loading: true,
    })
    const { status, data } = await request().post(loginApi.verifyCode, {
      verifyCode: values.captcha,
    })
    this.setState({
      loading: false,
    })
    if (status === 200) {
      message.success('登录成功')
      const token = data.token
      localStorage.setItem(TOKEN, token)
      // 正常登录
      const { from } = this.props.location.state || {}
      let { pathname = '', search = '' } = from || {}
      pathname = pathname ? `${pathname}${search}` : '/dashboard'
      this.props.history.push(pathname)
    }
  }

  render() {
    const { step, expired, loading, mail_address, currentTime, hasSend, btnLoading } = this.state
    return (
      <div className="login_page">
        <div className="logo"></div>
        <div className="login_form">
          <div className="login-logo">
          </div>
          {
            step === 1 &&
            <Form
              onFinish={this.handleSubmit}
              className="login_form_box"
              name="login"
              layout="vertical"
              ref={ref => this.form = ref}
              colon={false}
              hideRequiredMark={true}>
              <h1 className="login-title">登录</h1>
              <Form.Item
                name="name"
                label="用户名"
                rules={[{ required: true, message: '请输入用户名' }]}>
                <Input
                  className="input"
                  placeholder="请输入用户名"
                />
              </Form.Item>
              <Form.Item name="_pwd" label="密码" rules={[{ required: true, message: '请输入密码' }]}>
                <Input
                  className="input"
                  type="_pwd"
                  placeholder="请输入密码"
                />
              </Form.Item>
              <Form.Item shouldUpdate={true}>
                <Button
                  loading={loading}
                  type="primary"
                  htmlType="submit"
                  block
                  size="large"
                  className="login-form-button">
                  登&nbsp;录
                </Button>
              </Form.Item>
            </Form>
          }
          {/* 修改密码 */}
          {
            step === 2 &&
            <Form
              autoComplete="false"
              className="login_form_box"
              layout="vertical"
              onFinish={this.onModifyPwdFinish}
              ref={c => this.editform = c}
            >
              <h1 className={`login-title ${expired ? 'mb0' : ''}`}>设置新密码</h1>
              {
                expired &&
                <p className="tip">为保证账户安全，每90天须更换密码</p>
              }
              <Form.Item
                label="新密码:"
                name="newPwd"
                validateFirst
                rules={[
                  { required: true, message: '请输入新密码' },
                  {
                    type: 'string',
                    min: 8,
                    pattern: regexp._pwd,
                    message: '密码须为8位以上字母数字与特殊字符的组合',
                  },
                ]}
              >
                <Input.Password size="large" maxLength={30} placeholder="请输入新密码" />
              </Form.Item>
              <Form.Item
                label="确认新密码:"
                name="confirm_pwd"
                validateFirst
                rules={[
                  { required: true, message: '请输入新密码' },
                  {
                    type: 'string',
                    min: 8,
                    pattern: regexp._pwd,
                    message: '密码须为8位以上字母数字与特殊字符的组合',
                  },
                  ({ getFieldValue }) => ({
                    validator(_, value) {
                      if (getFieldValue('newPwd') === value) {
                        return Promise.resolve()
                      }
                      return Promise.reject(new Error('密码两次输入不一致'))
                    },
                  }),
                ]}
              >
                <Input.Password size="large" maxLength={30} placeholder="请输入新密码" />
              </Form.Item>
              <Form.Item >
                <Button
                  loading={loading}
                  type="primary"
                  htmlType="submit"
                  block
                  size="large"
                  className="login-form-button">
                  确&nbsp;定
                </Button>
              </Form.Item>
            </Form>
          }
          {/* 邮箱验证 */}
          {
            step === 3 &&
            <Form
              autoComplete="false"
              className="login_form_box"
              layout="vertical"
              onFinish={this.onEmailFormFinish}
              ref={c => this.emailForm = c}
            >
              <h1 className={`login-title`}>二次验证</h1>
              <Form.Item label={`邮箱：${mail_address}`}>
                <Row gutter={8}>
                  <Col span={14}>
                    <Form.Item
                      name="captcha"
                      noStyle
                      rules={[{ required: true, message: '请输入验证码' }]}
                    >
                      <Input maxLength={6} size="large" prefix={<MailOutlined/>} placeholder={'请输入验证码'} />
                    </Form.Item>
                  </Col>
                  <Col span={10}>
                    <Button
                      size="large"
                      disabled={hasSend}
                      block
                      onClick={this.getCode}
                      loading={btnLoading}>
                      {
                        hasSend ? `${currentTime}s后重新发送` : '获取验证码'
                      }
                    </Button>
                  </Col>
                </Row>
              </Form.Item>
              <Form.Item >
                <Button
                  loading={loading}
                  type="primary"
                  htmlType="submit"
                  block
                  size="large"
                  className="login-form-button">
                  确&nbsp;定
                </Button>
              </Form.Item>
            </Form>
          }
        </div>
      </div>
    )
  }
}

const totalTime = 60
